<?php
/**
* Authorization item controller class file.
*
* @author Christoffer Niska <cniska@live.com>
* @copyright Copyright &copy; 2010 Christoffer Niska
* @since 0.5
*/
class AuthItemController extends Controller
{
	/**
	 * @var CAuthItem the currently loaded data model instance.
	 */
	private $_model;

	/**
	* @var Authorization component
	*/
	private $_auth;

	/**
	* Initialization.
	*/
	public function init()
	{
		$this->_auth = Yii::app()->getModule('authorization')->auth;
	}

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',
				'actions'=>array(
					'createOperation',
					'updateOperation',
					'deleteOperation',
					'createTask',
					'updateTask',
					'deleteTask',
					'createRole',
					'updateRole',
					'deleteRole',
					'removeChild',
					'assign',
					'revoke',
				),
				'users'=>array($this->_auth->superUser),
			),
			array('deny',
				'users'=>array('*'),
			),
		);
	}

	/**
	* Creates an operation.
	*/
	public function actionCreateOperation()
	{
		// Create the auth item form
	    $form = new CForm('application.modules.authorization.views.authItem.form', new AuthItemForm);

	    // Form is submitted and data is valid, redirect the user
	    if( $form->submitted()===true && $form->validate()===true )
		{
			// Create the operation and redirect
			$this->_auth->createAuthItem($form->model->name, CAuthItem::TYPE_OPERATION, $form->model->description, $form->model->bizRule, $form->model->data);
			$this->redirect(array('main/operations'));
		}

		// Set breadcrumbs
		$this->breadcrumbs = array(
			Yii::t('breadcrumb', 'Access control')=>array('/authorization/main'),
			Yii::t('breadcrumb', 'Operations')=>array('main/operations'),
			Yii::t('breadcrumb', 'Create'),
		);

		// Render the view
		$this->render('create', array(
			'form'=>$form,
			'heading'=>Yii::t('authItem', 'Create Operation'),
		));
	}

	/**
	* Updates an operation.
	*/
	public function actionUpdateOperation()
	{
		// Create the auth item form
	    $form = new CForm('application.modules.authorization.views.authItem.form', new AuthItemForm);

		// Create a from to add a child for the auth item
	    $childForm = new CForm(array(
		    'elements'=>array(
		        'child'=>array(
		            'type'=>'dropdownlist',
		            'items'=>$this->_auth->getTaskSelectOptions(),
		        ),
		    ),
		    'buttons'=>array(
		        'submit'=>array(
		            'type'=>'submit',
		            'label'=>Yii::t('authItem', 'Add'),
		        ),
		    ),
		), new ChildForm);

	    // Form is submitted and data is valid, redirect the user
	    if( $form->submitted()===true && $form->validate()===true )
		{
			// Update the operation and redirect
			$this->_auth->updateAuthItem($_GET['name'], $form->model->name, $form->model->description, $form->model->bizRule, $form->model->data);
			$this->redirect(array('main/operations'));
		}

		// Get the authorization item
		$model = $this->loadModel();

		// Child form is submitted and data is valid, redirect the user to the same page
		if( $childForm->submitted()===true && $childForm->validate()===true )
		{
			$this->_auth->addAuthItemChild($_GET['name'], $childForm->model->child);
			$this->redirect(array('authItem/updateOperation', 'name'=>$_GET['name']));
		}

		// Set the values for the form fields
		$form->model->name = $model->name;
		$form->model->description = $model->description;
		$form->model->bizRule = $model->bizRule!=='NULL' ? $model->bizRule : '';
		$form->model->data = $model->data!==NULL ? serialize($model->data) : '';

		// Set the breadcrumbs
		$this->breadcrumbs = array(
			Yii::t('breadcrumb', 'Access control')=>array('/authorization/main'),
			Yii::t('breadcrumb', 'Operations')=>array('main/operations'),
			$model->name,
			Yii::t('breadcrumb', 'Update'),
		);

		// Render the view
		$this->render('update', array(
			'model'=>$model,
			'children'=>$this->_auth->getAuthItemChildren($model),
			'form'=>$form,
			'childForm'=>$childForm,
			'auth'=>$this->_auth,
		));
	}

	/**
	 * Deletes an operation.
	 */
	public function actionDeleteOperation()
	{
		// We only allow deletion via POST request
		if( Yii::app()->request->isPostRequest===true )
		{
			$this->_auth->deleteAuthItem($_GET['name']);

			// if AJAX request, we should not redirect the browser
			if( isset($_POST['ajax'])===false )
				$this->redirect(array('main/operations'));
		}
		else
		{
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
		}
	}

	/**
	* Creates a task.
	*/
	public function actionCreateTask()
	{
		// Create the auth item form
	    $form = new CForm('application.modules.authorization.views.authItem.form', new AuthItemForm);

	    // Form is submitted and data is valid, redirect the user
	    if( $form->submitted()===true && $form->validate()===true )
		{
			// Create the task and redirect
			$this->_auth->createAuthItem($form->model->name, CAuthItem::TYPE_TASK, $form->model->description, $form->model->bizRule, $form->model->data);
			$this->redirect(array('main/tasks'));
		}

		// Set breadcrumbs
		$this->breadcrumbs = array(
			Yii::t('breadcrumb', 'Access control')=>array('/authorization/main'),
			Yii::t('breadcrumb', 'Tasks')=>array('main/tasks'),
			Yii::t('breadcrumb', 'Create'),
		);

		// Render the view
		$this->render('create', array(
			'form'=>$form,
			'heading'=>Yii::t('authItem', 'Create Task'),
		));
	}

	/**
	* Updates a task.
	*/
	public function actionUpdateTask()
	{
		// Create the auth item form
	    $form = new CForm('application.modules.authorization.views.authItem.form', new AuthItemForm);

	    // Form is submitted and data is valid, redirect the user
	    if( $form->submitted()===true && $form->validate()===true )
		{
			// Update the task and redirect
			$this->_auth->updateAuthItem($_GET['name'], $form->model->name, $form->model->description, $form->model->bizRule, $form->model->data);
			$this->redirect(array('main/tasks'));
		}

		// Get the authorization item
		$model = $this->loadModel();

		// Set the values for the form fields
		$form->model->name = $model->name;
		$form->model->description = $model->description;
		$form->model->bizRule = $model->bizRule!=='NULL' ? $model->bizRule : '';
		$form->model->data = $model->data!==NULL ? serialize($model->data) : '';

		// Set the breadcrumbs
		$this->breadcrumbs = array(
			Yii::t('breadcrumb', 'Access control')=>array('/authorization/main'),
			Yii::t('breadcrumb', 'Tasks')=>array('main/tasks'),
			$model->name,
			Yii::t('breadcrumb', 'Update'),
		);

		// Render the view
		$this->render('update', array(
			'model'=>$model,
			'children'=>$this->_auth->getAuthItemChildren($model),
			'form'=>$form,
			'auth'=>$this->_auth,
		));
	}

	/**
	 * Deletes a task.
	 */
	public function actionDeleteTask()
	{
		// We only allow deletion via POST request
		if( Yii::app()->request->isPostRequest===true )
		{
			$this->_auth->deleteAuthItem($_GET['name']);

			// if AJAX request, we should not redirect the browser
			if( isset($_POST['ajax'])===false )
				$this->redirect(array('main/tasks'));
		}
		else
		{
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
		}
	}

	/**
	* Creates a role.
	*/
	public function actionCreateRole()
	{
		// Create the auth item form
	    $form = new CForm('application.modules.authorization.views.authItem.form', new AuthItemForm);

	    // Form is submitted and data is valid, redirect the user
	    if( $form->submitted()===true && $form->validate()===true )
		{
			// Create the role and redirect
			$this->_auth->createRole($form->model->name, $form->model->description, $form->model->bizRule, $form->model->data);
			$this->redirect(array('main/roles'));
		}

		// Set breadcrumbs
		$this->breadcrumbs = array(
			Yii::t('breadcrumb', 'Access control')=>array('/authorization/main'),
			Yii::t('breadcrumb', 'Roles')=>array('main/roles'),
			Yii::t('breadcrumb', 'Create'),
		);

		// Render the view
		$this->render('create', array(
			'form'=>$form,
			'heading'=>Yii::t('authItem', 'Create Role'),
		));
	}

	/**
	* Updates a role.
	*/
	public function actionUpdateRole()
	{
		// Create the auth item form
	    $form = new CForm('application.modules.authorization.views.authItem.form', new AuthItemForm);

	    // Form is submitted and data is valid, redirect the user
	    if( $form->submitted()===true && $form->validate()===true )
		{
			// Update the role and redirect
			$this->_auth->updateRole($_GET['name'], $form->model->name, $form->model->description, $form->model->bizRule, $form->model->data);
			$this->redirect(array('main/roles'));
		}

		// Get the authorization item
		$model = $this->loadModel();

		// Set the values for the form fields
		$form->model->name = $model->name;
		$form->model->description = $model->description;
		$form->model->bizRule = $model->bizRule!=='NULL' ? $model->bizRule : '';
		$form->model->data = $model->data!==NULL ? serialize($model->data) : '';

		// Set the breadcrumbs
		$this->breadcrumbs = array(
			Yii::t('breadcrumb', 'Access control')=>array('/authorization/main'),
			Yii::t('breadcrumb', 'Roles')=>array('main/roles'),
			$model->name,
			Yii::t('breadcrumb', 'Update'),
		);

		// Render the view
		$this->render('update', array(
			'model'=>$model,
			'children'=>$this->_auth->getAuthItemChildren($model),
			'form'=>$form,
			'auth'=>$this->_auth,
		));
	}

	/**
	 * Deletes a role.
	 */
	public function actionDeleteRole()
	{
		// We only allow deletion via POST request
		if( Yii::app()->request->isPostRequest===true )
		{
			$this->_auth->deleteRole($_GET['name']);

			// if AJAX request, we should not redirect the browser
			if( isset($_POST['ajax'])===false )
				$this->redirect(array('main/roles'));
		}
		else
		{
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
		}
	}

	/**
	* Removes a child from an authorization item.
	*/
	public function actionRemoveChild()
	{
		// We only allow deletion via POST request
		if( Yii::app()->request->isPostRequest===true )
		{
			$this->_auth->removeAuthItemChild($_GET['name'], $_GET['child']);

			// if AJAX request, we should not redirect the browser
			if( isset($_POST['ajax'])===false )
				$this->redirect(array('main/permissions'));
		}
		else
		{
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
		}
	}

	/**
	* Adds a child to an authorization item.
	*/
	public function actionAssign()
	{
		$model = $this->loadModel();

		if( isset($_GET['child'])===true && $model->hasChild($_GET['child'])===false )
			$model->addChild($_GET['child']);

		$this->redirect(array('main/permissions'));
	}

	/**
	* Removes a child from an authorization item.
	*/
	public function actionRevoke()
	{
		$model = $this->loadModel();

		if( isset($_GET['child'])===true && $model->hasChild($_GET['child'])===true )
			$model->removeChild($_GET['child']);

		$this->redirect(array('main/permissions'));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 */
	public function loadModel()
	{
		if( $this->_model===null )
		{
			if( isset($_GET['name'])===true )
				$this->_model = $this->_auth->authManager->getAuthItem($_GET['name']);
			if( $this->_model===null )
				throw new CHttpException(404,'The requested page does not exist.');
		}

		return $this->_model;
	}
}
